package com.xdjk.networkdemo.net;

import android.app.Activity;
import android.app.ProgressDialog;
import android.widget.Toast;

import com.orhanobut.logger.Logger;
import com.xdjk.networkdemo.listener.LoadingDialogListener;
import com.xdjk.networkdemo.net.bean.DownInfo;
import com.xdjk.networkdemo.net.bean.DownState;
import com.xdjk.networkdemo.net.db.DBUtils;
import com.xdjk.networkdemo.utils.DialogUtils;

import rx.Subscriber;

/**
 * Created by Tamic on 2016-08-02.
 */
public abstract class DownloadCallBack<ResponseBody> extends Subscriber<ResponseBody> implements LoadingDialogListener {
    private ProgressDialog progressDialog;
    private Activity mActivity;
    private DownInfo downInfo;

    public DownloadCallBack(Activity activity) {
        this.mActivity = activity;
        progressDialog = DialogUtils.createProgressDialog(activity, "", "文件下载中..");

    }

    @Override
    public void onStart() {
        super.onStart();
        showLoading();
    }

    @Override
    public void onNext(ResponseBody responseBody) {

    }

    @Override
    public void onError(Throwable e) {
        hideLoading();
    }

    @Override
    public void onCompleted() {

    }

    public void onErrorFail(Throwable e) {
        hideLoading();
        onDownloadFail(e);
    }

    @Override
    public void showLoading() {
        if (!mActivity.isFinishing()) {
            progressDialog.show();
        }
    }

    @Override
    public void hideLoading() {
        progressDialog.cancel();
    }

    abstract public void onDownloadSucess();

    abstract public void onDownloadFail(Throwable e);

    public void onProgressUpdate(long bytesWritten, long contentLength, boolean b) {
        if (!b) {
            int progress = (int) (bytesWritten * 100 / contentLength);
            if (bytesWritten % 100 == 0) {
                Logger.d("progress=" + progress, Toast.LENGTH_SHORT);
                progressDialog.setProgress(progress);

                downInfo.setState(DownState.DOWN);
                downInfo.setReadLength(bytesWritten);
                downInfo.setCountLength(contentLength);
                DBUtils.getInstance().update(downInfo);
            }
        } else {
            progressDialog.setProgress(100);
            hideLoading();
            onDownloadSucess();
            downInfo.setReadLength(contentLength);
            downInfo.setState(DownState.FINISH);
            DBUtils.getInstance().update(downInfo);
        }
    }

    public DownInfo getDownInfo() {
        return downInfo;
    }

    public void setDownInfo(DownInfo downInfo) {
        this.downInfo = downInfo;
    }
}
